package com.lhk.appframework.utils;

import java.util.List;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.widget.Toast;

public class UtilsSms {
	
	
	
	/** 
	* @Description: 发送短信
	* @author liuhaikang 
	* @date 2015-10-22 下午5:55:00 
	* @param context
	* @param phoneNum
	* @param smsInfo 
	*/
	public static void sendSms(Context context, String phoneNum, String smsInfo){
		
        PendingIntent sentPI = getSentIntentDefault(context);
		PendingIntent deliverPI = getDeliverIntentDefault(context);
		
		sendSms(context, phoneNum, smsInfo, sentPI, deliverPI);
	}
	
	public static void sendSms(final Context context, String phoneNum, String smsInfo, PendingIntent sentPI, PendingIntent deliverPI){
		//获取短信管理器   
        android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault(); 
        //拆分短信内容（手机短信长度限制）    
        List<String> divideContents = smsManager.divideMessage(smsInfo);   
        for (String text : divideContents) {    
			smsManager.sendTextMessage(phoneNum, null, text, sentPI, deliverPI);    
        }  
	}
	
	
	private static PendingIntent getDeliverIntentDefault(final Context context){
		//处理返回的接收状态   
		String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";  
		// create the deilverIntent parameter  
		Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);  
		PendingIntent deliverPI = PendingIntent.getBroadcast(context, 0,  
		       deliverIntent, 0);  
		context.registerReceiver(new BroadcastReceiver() {  
		   @Override  
		   public void onReceive(Context _context, Intent _intent) {  
		       Toast.makeText(context,  "收信人已经成功接收", Toast.LENGTH_SHORT) .show();  
		   }  
		}, new IntentFilter(DELIVERED_SMS_ACTION));
		return deliverPI;  
	}
	
	private static PendingIntent getSentIntentDefault(final Context context){
		String SENT_SMS_ACTION = "SENT_SMS_ACTION";  
		Intent sentIntent = new Intent(SENT_SMS_ACTION);  
		PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, sentIntent,  0);  
		// register the Broadcast Receivers  
		context.registerReceiver(new BroadcastReceiver() {  
		    @Override  
		    public void onReceive(Context _context, Intent _intent) {  
		        switch (getResultCode()) {  
		        case Activity.RESULT_OK:  
		            Toast.makeText(context,  "短信发送成功", Toast.LENGTH_SHORT)  .show();  
		        break;  
		        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:  
		        break;  
		        case SmsManager.RESULT_ERROR_RADIO_OFF:  
		        break;  
		        case SmsManager.RESULT_ERROR_NULL_PDU:  
		        break;  
		        }  
		    }  
		}, new IntentFilter(SENT_SMS_ACTION)); 
		
		return sentPI;
	}
}
